import { ref, computed, watch } from 'vue'

const STORAGE_KEY = 'pixiu-records'

// 记录数据
const records = ref([])

// 从本地存储加载
const loadFromLocalStorage = () => {
  const saved = localStorage.getItem(STORAGE_KEY)
  if (saved) {
    try {
      records.value = JSON.parse(saved)
    } catch (e) {
      console.error('加载数据失败', e)
    }
  }
}

// 保存到本地存储
const saveToLocalStorage = () => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(records.value))
}

// 监听变化自动保存
watch(records, saveToLocalStorage, { deep: true })

// 初始化加载
loadFromLocalStorage()

export const useRecords = () => {
  // 本月收入
  const monthlyIncome = computed(() => {
    const currentMonth = new Date().toISOString().substring(0, 7)
    return records.value
      .filter(r => r.type === 'income' && r.date.substring(0, 7) === currentMonth)
      .reduce((sum, r) => sum + r.amount, 0)
  })

  // 本月支出
  const monthlyExpense = computed(() => {
    const currentMonth = new Date().toISOString().substring(0, 7)
    return records.value
      .filter(r => r.type === 'expense' && r.date.substring(0, 7) === currentMonth)
      .reduce((sum, r) => sum + r.amount, 0)
  })

  // 本月结余
  const monthlyBalance = computed(() => {
    return monthlyIncome.value - monthlyExpense.value
  })

  // 添加记录
  const addRecord = (record) => {
    records.value.push(record)
  }

  // 删除记录
  const deleteRecord = (id) => {
    const index = records.value.findIndex(r => r.id === id)
    if (index > -1) {
      records.value.splice(index, 1)
    }
  }

  return {
    records,
    monthlyIncome,
    monthlyExpense,
    monthlyBalance,
    addRecord,
    deleteRecord
  }
}
